package com.hzcx.app.simplechat.ui.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.ui.chat.ChatShareUserActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatFriendDeleteEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.friend.event.DeleteFriendEvent;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.publicui.CaptureResultActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.ShareActivity;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.ui.setting.ReportActivity;
import com.hzcx.app.simplechat.ui.user.adapter.MomentImgAdapter;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.ui.user.contract.UserInfoContract;
import com.hzcx.app.simplechat.ui.user.enums.SexEnum;
import com.hzcx.app.simplechat.ui.user.event.UserLableEvent;
import com.hzcx.app.simplechat.ui.user.event.UserRemarkEvent;
import com.hzcx.app.simplechat.ui.user.presenter.UserInfoPresenter;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.down.DownLoadUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.image.ImageUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.qrcode.QRCodeParseUtils;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.hzcx.app.simplechat.view.autogridview.PhotoProgressUi;
import com.hzcx.app.simplechat.view.imageview.RoundImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import indi.liyi.viewer.ImageViewer;

/**
 * 用户信息界面
 */
public class UserInfoActivity extends BaseActivity<UserInfoPresenter> implements UserInfoContract.View {

    public static final String INTENT_USER_ID = "INTENT_USER_ID";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.iv_head)
    RoundImageView ivHead;
    @BindView(R.id.tv_to_chat)
    TextView tvToChat;
    @BindView(R.id.tv_remark_name)
    TextView tvRemarkName;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_user_id)
    TextView tvUserId;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.ll_sign)
    LinearLayout llSign;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.tv_moment)
    TextView tvMoment;
    @BindView(R.id.rv_moment_img)
    RecyclerView rvMomentImg;
    @BindView(R.id.tv_moment_background)
    TextView tvMomentBackground;
    @BindView(R.id.tv_black)
    TextView tvBlack;
    @BindView(R.id.switch_black)
    Switch switchBlack;
    @BindView(R.id.tv_report)
    TextView tvReport;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.cons_main)
    ConstraintLayout consMain;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;
    @BindView(R.id.view_bottom_line)
    View viewBottomLine;
    @BindView(R.id.tv_banned)
    TextView tvBanned;


    private int userId;
    private UserInfoBean userInfoBean;
    private HxUserInfoBean hxUserInfoBean;

    private List<UserInfoBean.DynamicDataBean> imgData;
    private MomentImgAdapter imgAdapter;

    private boolean isBlackReady = false;
    private ImageView saveImageView;

    @Override
    public int getLayout() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initPresenter() {
        mPresenter = new UserInfoPresenter();
    }

    @Override
    public void initView() {
        imageViewer.imageLoader(new PhotoLoader());
        tvTitle.setText("个人信息");
        ivTitleRight.setImageResource(R.mipmap.ic_icon_title_more);

        imgData = new ArrayList<>();
        imgAdapter = new MomentImgAdapter(imgData);
        rvMomentImg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rvMomentImg.setAdapter(imgAdapter);

    }

    @Override
    public void initData() {
        userId = getIntent().getIntExtra(INTENT_USER_ID, 0);
        mPresenter.getUserInfo(this, userId);

        switchBlack.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!isBlackReady) {
                return;
            }
            if (b) {
                mPresenter.putUserInBlack(UserInfoActivity.this, userId);
            } else {
                mPresenter.putUserOutBlack(UserInfoActivity.this, userId);
            }
            isBlackReady = false;
        });
    }

    @OnClick({R.id.tv_delete, R.id.tv_remark, R.id.tv_moment, R.id.tv_report, R.id.tv_to_chat, R.id.tv_title_right, R.id.tv_moment_background,
            R.id.iv_head})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_delete: // 删除好友
                showDeleteDialog();
                break;

            case R.id.tv_remark: // 用户备注
                startActivity(new Intent(this, UserRemarkActivity.class)
                        .putExtra(UserRemarkActivity.INTENT_USER_INFO, userInfoBean));
                break;

            case R.id.tv_moment: // 朋友圈
            case R.id.tv_moment_background:
                startActivity(new Intent(this, UserMomentActivity.class)
                        .putExtra(UserMomentActivity.INTENT_USER_INFO, userInfoBean));
                break;

            case R.id.tv_report: // 举报
                startActivity(new Intent(this, ReportActivity.class)
                        .putExtra(ReportActivity.INTENT_USER_ID, userInfoBean.getMember_id()));
                break;

            case R.id.tv_to_chat: // 聊天
                ChatUtil.getInstance().toChatUi(this, hxUserInfoBean);
                break;

            case R.id.tv_title_right: // 右上角分享
                startActivity(new Intent(this, ShareActivity.class)
                        .putExtra(ShareActivity.INTENT_USER_ID, userId));
                break;

            case R.id.iv_head: // 头像点击
                List<String> list = new ArrayList<>();
                list.add(userInfoBean.getBavatar());
                imageViewer.overlayStatusBar(true)
                        .imageData(list)
                        .loadProgressUI(new PhotoProgressUi())
                        .setOnItemLongPressListener((position, imageView) -> {
                            saveImgToPhoto(imageView);
                            return false;
                        })
                        .watch(0);
                break;
        }
    }

    /**
     * 保存图片到相册
     */
    private void saveImgToPhoto(ImageView imageView) {
        saveImageView = imageView;
        new Thread(() -> {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
            Message msg = new Message();
            msg.what = 0x03;
            msg.obj = result;
            handler.sendMessage(msg);
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x02) {
                String result = msg.obj == null ? null : (String) msg.obj;
                LogUtils.d(result);
                if (EmptyUtils.isEmpty(result)) {
                    showError("未识别到二维码信息");
                    return;
                }
                if (result.contains("chat_number")) {
                    // 如果是多聊二维码，调用接口
                    mPresenter.getUserInfoByQrCode(UserInfoActivity.this, result);
                } else if (TextHttpUtil.hasNetUrlHead(result)) {
                    // 网页链接，跳转到web界面
                    startActivity(new Intent(UserInfoActivity.this, WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, result));
                } else {
                    // 都不是，直接展示结果
                    startActivity(new Intent(UserInfoActivity.this, CaptureResultActivity.class)
                            .putExtra(CaptureResultActivity.INTENT_RESULT, result));
                }
            } else if (msg.what == 0x03) {
                String qrcode = (String) msg.obj;
                List<String> list = new ArrayList<>();
                list.add("发送给朋友");
                list.add("收藏");
                list.add("保存到相册");
                if (EmptyUtils.isNotEmpty(qrcode)) {
                    list.add("识别图中二维码");
                }
                PublicRoundDialog roundDialog = new PublicRoundDialog(UserInfoActivity.this, list, (pos, menu) -> {
                    switch (menu) {
                        case "发送给朋友":
                            startActivity(new Intent(UserInfoActivity.this, ChatShareUserActivity.class)
                                    .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 5));
                            break;

                        case "收藏":
                            collectImg();
                            break;
                        case "保存到相册":
                            ImageUtil.saveMyBitmap(UserInfoActivity.this, ((BitmapDrawable) saveImageView.getDrawable()).getBitmap(),
                                    "chat_" + System.currentTimeMillis() + ".jpg");
                            break;
                        case "识别图中二维码":
                            if (EmptyUtils.isEmpty(qrcode)) {
                                showError("未识别到二维码信息");
                                return;
                            }
                            if (qrcode.contains("chat_number")) {
                                // 如果是多聊二维码，调用接口
                                mPresenter.getUserInfoByQrCode(UserInfoActivity.this, qrcode);
                            } else if (TextHttpUtil.hasNetUrlHead(qrcode)) {
                                // 网页链接，跳转到web界面
                                startActivity(new Intent(UserInfoActivity.this, WebViewActivity.class)
                                        .putExtra(WebViewActivity.INTENT_WEB_URL, qrcode));
                            } else {
                                // 都不是，直接展示结果
                                startActivity(new Intent(UserInfoActivity.this, CaptureResultActivity.class)
                                        .putExtra(CaptureResultActivity.INTENT_RESULT, qrcode));
                            }
                            break;
                    }
                });
                roundDialog.show();
            }
        }
    };

    private void showDeleteDialog() {
        showConfirmDialog("提示", "是否删除好友？", null, () ->
                mPresenter.deleteFriend(UserInfoActivity.this, userId));
    }

    /**
     * 收藏头像
     */
    private void collectImg() {
        DownLoadUtil.downLoadImg(userInfoBean.getBavatar(), new DownLoadUtil.OnDownLoadListener() {
            @Override
            public void success(String path) {
                mPresenter.upLoadImg(UserInfoActivity.this, path);
            }

            @Override
            public void fail() {
                showError("图片下载失败");
            }
        });
    }

    /**
     * 用户信息获取成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data) {
        userInfoBean = data;
        loadChatUserData();
        GlideUtils.loadImg(this, data.getAvatar(), ivHead);

        if (EmptyUtils.isEmpty(data.getRemarks_name())) {
            tvRemarkName.setText(data.getNickname());
            tvNickName.setVisibility(View.GONE);
        } else {
            tvRemarkName.setText(data.getRemarks_name());
            tvNickName.setText("昵称：" + data.getNickname());
            tvNickName.setVisibility(View.VISIBLE);
        }

        if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_GRIL)) {
            ivSex.setImageResource(R.mipmap.ic_icon_sex_gril);
            ivSex.setVisibility(View.VISIBLE);
        } else if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_BOY)) {
            ivSex.setImageResource(R.mipmap.ic_icon_sex_boy);
            ivSex.setVisibility(View.VISIBLE);
        } else {
            ivSex.setVisibility(View.GONE);
        }
        tvUserId.setText(getResources().getString(R.string.app_name) + "号：" + data.getChatnumber());
        tvCity.setText(data.getArea());
        tvSign.setText("个性签名：" + data.getBio());
        if (data != null && data.getDynamic_data() != null && data.getDynamic_data().size() > 0) {
            imgData.addAll(data.getDynamic_data());
            imgAdapter.notifyDataSetChanged();
        }

        if (data.getIs_black() == 1) {
            switchBlack.setChecked(true);
        } else {
            switchBlack.setChecked(false);
        }

        isBlackReady = true;

        consMain.setVisibility(View.VISIBLE);

        // 如果是助手，则隐藏下面的界面
        if (data.getIs_assistant() == 1) {
            tvRemark.setVisibility(View.GONE);
            tvBlack.setVisibility(View.GONE);
            switchBlack.setVisibility(View.GONE);
            tvReport.setVisibility(View.GONE);
            tvDelete.setVisibility(View.GONE);
            viewBottomLine.setVisibility(View.GONE);
        }

        // 对方账号如果被封禁，则无法发送消息
        if (data.getIs_banned() == 1) {
            tvToChat.setBackgroundResource(R.drawable.btn_send_code_bg_normal);
            tvToChat.setTextColor(getResources().getColor(R.color.color_282F3E));
            tvToChat.setEnabled(false);
            tvBanned.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新本地保存的用户数据
     */
    private void loadChatUserData() {
        hxUserInfoBean = new HxUserInfoBean();
        hxUserInfoBean.setHxusername(userInfoBean.getHxusername());
        hxUserInfoBean.setAvatar(userInfoBean.getAvatar());
        hxUserInfoBean.setBy_remarks_name(userInfoBean.getBy_remarks_name());
        hxUserInfoBean.setMember_id(userInfoBean.getMember_id());
        hxUserInfoBean.setNickname(userInfoBean.getNickname());
        hxUserInfoBean.setRemarks_name(userInfoBean.getRemarks_name());
        hxUserInfoBean.setMyUserId(UserInfoUtil.getUserId());
        hxUserInfoBean.setIs_assistant(userInfoBean.getIs_assistant());

        LitePal.where("hxusername=? and myUserId=?", hxUserInfoBean.getHxusername(), UserInfoUtil.getUserId() + "").findFirstAsync(HxUserInfoBean.class)
                .listen(userInfoBean -> {
                    if (userInfoBean == null) {
                        hxUserInfoBean.save();
                    } else {
                        userInfoBean.setRemarks_name(this.userInfoBean.getRemarks_name());
                        userInfoBean.setAvatar(this.userInfoBean.getAvatar());
                        userInfoBean.setBy_remarks_name(this.userInfoBean.getBy_remarks_name());
                        userInfoBean.setMember_id(this.userInfoBean.getMember_id());
                        userInfoBean.setNickname(this.userInfoBean.getNickname());
                        userInfoBean.setIs_assistant(this.userInfoBean.getIs_assistant());
                        userInfoBean.save();
                    }
                });
    }

    /**
     * 删除好友成功
     */
    @Override
    public void deleteSuccess() {
        EventBus.getDefault().post(new DeleteFriendEvent(userId));
        EventBus.getDefault().post(new ChatFriendDeleteEvent(userId));
        showError("删除成功");
        finish();
    }

    /**
     * 加入黑名单成功
     */
    @Override
    public void inBlackSuccess() {
        isBlackReady = true;
    }

    /**
     * 加入黑名单失败
     */
    @Override
    public void inBlackFail() {
        switchBlack.setChecked(!switchBlack.isChecked());
        isBlackReady = true;
    }

    /**
     * 移除黑名单成功
     */
    @Override
    public void outBlackSuccess() {
        isBlackReady = true;
    }

    /**
     * 图片收藏成功
     */
    @Override
    public void collectSuccess() {
        showError("收藏成功");
    }

    /**
     * 图片上传成功
     *
     * @param data
     */
    @Override
    public void upLoadImgSuccess(UpLoadImgBean data) {
        // 图片上传成功，收藏图片
        mPresenter.addChatCollect(this, null, data.getUrl(), userInfoBean.getMember_id());
    }

    /**
     * 根据二维码获取用户信息成功
     *
     * @param data
     */
    @Override
    public void userInfoResultByCode(UserInfoBean data) {
        if (data.getMember_id() == UserInfoUtil.getUserId()) {
            startActivity(new Intent(this, MineUserInfoActivity.class));
            return;
        }
        if (data.getIs_buddy() == 1) {
            startActivity(new Intent(this, UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
        } else {
            startActivity(new Intent(this, AddFriendActivity.class)
                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
                    .putExtra(AddFriendActivity.INTENT_TYPE, 2));
        }
    }

    /**
     * 用户备注名设置成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setRemarkNameSuccess(UserRemarkEvent event) {
        userInfoBean = event.getBean();
        if (EmptyUtils.isEmpty(userInfoBean.getRemarks_name())) {
            tvRemarkName.setText(userInfoBean.getNickname());
            tvNickName.setVisibility(View.GONE);
        } else {
            tvRemarkName.setText(userInfoBean.getRemarks_name());
            tvNickName.setText("昵称：" + userInfoBean.getNickname());
            tvNickName.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 用户标签修改成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userLableSuccess(UserLableEvent event) {
        try {
            if (userInfoBean.getLable_name_arr() == null) {
                userInfoBean.setLable_name_arr(new ArrayList<>());
            }
            userInfoBean.getLable_name_arr().clear();
            userInfoBean.getLable_name_arr().addAll(event.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转发选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectUserResult(ChatShareUserEvent event) {
        if (userInfoBean == null) {
            showError("暂未获取到用户信息，请稍后重试");
            return;
        }
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(userInfoBean.getHxusername(),
                ChatUtil.getConversationType(ChatConstant.CHATTYPE_SINGLE), true);
        if (userInfoBean.getIs_del() == 1) {
            showError("您还不是对方好友，请先加对方好友");
            return;
        }
        if (event.getTag() == 5) {
            LogUtils.d("分享名片");
            if (userInfoBean == null) {
                showError("暂未获取到用户信息，请稍后重试");
                return;
            }
            showLoading();
            DownLoadUtil.downLoadImg(userInfoBean.getBavatar(), new DownLoadUtil.OnDownLoadListener() {
                @Override
                public void success(String path) {
                    hideLoading();
                    ChatUtil.getInstance().sendImgMessage(UserInfoActivity.this,path, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE,
                            event.getBean().getMember_id(), EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() :
                                    event.getBean().getRemarks_name(), null);
                    showError("发送成功");
                }

                @Override
                public void fail() {
                    hideLoading();
                    showError("图片下载失败");
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
